package com.viewshine.nettydemo.staticMethod.nettyClient;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName BasicsEchoClientHandler
 * @Author rhb
 * @Description 基础/静态 客户端处理器
 * @Date 2019-01-17 16:20
 * @Version 1.0
 **/
@Slf4j
@ChannelHandler.Sharable
public class BasicsEchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    /**
     * 连接上服务器
     * @param ctx
     * @throws Exception
     */
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送的字符串
        Map map = new HashMap();
        map.put("aa",1);
        map.put("bb","嘟嘟");
        String cmd = JSON.toJSONString(map);
        log.debug("发送命令【{}】", cmd);
        byte[] bytes = cmd.getBytes();
        ByteBuf clientMessage = Unpooled.buffer(bytes.length);
        clientMessage.writeBytes(bytes);
        ctx.writeAndFlush(clientMessage);
    }

    /**
     *
     * @param ctx
     * @param byteBuf
     * @throws Exception
     */
    protected void messageReceived(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
        System.out.println("BasicsEchoClientHandler...messageReceived..............");
        try {
            ByteBuf buf = (ByteBuf) byteBuf;
            System.out.println("BasicsEchoClientHandler....channelRead..........:"+buf.toString(Charset.forName("UTF-8")));
            byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
            String message = new String(req, "UTF-8");
            log.debug("message=【{}】",message);
        }finally {
            ctx.close();
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.debug("BasicsEchoClientHandler.....err close");
        cause.printStackTrace();
        ctx.close();
    }

}
